package com.lj.frame;


import com.lj.tools.exception.YerException;
import com.lj.tools.response.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 自定义异常
     * */
    @ExceptionHandler(value = YerException.class)
    @ResponseBody
    public Result yerExceptionHandler(YerException e){
        log.error("业务异常", e);
        return Result.error().setContent(e.getMessage());
    }

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Result exceptionHandler(Exception e){
        log.error("未知异常! 原因是:", e);
        return Result.error().setContent(e.getMessage());
    }

    @ExceptionHandler(value = RuntimeException.class)
    @ResponseBody
    public Result runtimeExceptionHandler(RuntimeException e){
        log.error("未知异常! 原因是:", e);
        return Result.error().setContent(e.getMessage());
    }


    /**
     * spring boot 函数参数验证
     * */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    @ResponseBody
    public Result methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e){
        log.error("参数异常", e);
        List<ObjectError> objectErrorList = e.getBindingResult().getAllErrors();
        StringBuilder builder = new StringBuilder();
        objectErrorList.forEach( error -> {
            builder.append(error.getDefaultMessage());
            builder.append(";");
        });
        return Result.error().setContent(builder.toString());
    }

}
